<?php

class Admin_UserController extends Zend_Controller_Action
{
	private $_auth;
	private $_acl;
    public function init(){
        $acl                = new My_Acl();
        $auth               = $acl->checkAllowed($this->_request);
        $this->_auth        = $auth->getIdentity();
        $this->view->auth   = $this->_auth;
        $this->_acl         = $acl;
        $this->view->acl    = $this->_acl;
    }
    public function indexAction(){
        $modelRole  = new Admin_Model_Role();
        $modelUser  = new Admin_Model_User();
        $userList   = $modelUser->getAllData()->toArray();
        foreach($userList as $key => $row){
            $userList[$key]['roleList']   = $modelRole->getDataByUserId($row['userId'])->toArray();
        }
        
        $this->view->userList = $userList;
        $this->view->userCheck = $modelUser->getDataById($this->_auth['userId']);
    }
    public function deleteAction(){
        $userId = $this->_getParam('id', 0);
        $modelUser = new Admin_Model_User();
        $userCheck = $modelUser->getDataById($userId);
        if($userCheck){
            $this->view->userCheck = $userCheck;
            if($this->getRequest()->isPost()){
                $del = $this->getRequest()->getPost('del');
                if($del == 'Có'){
                    $userId = $this->getRequest()->getPost('userId');
                    $modelUser->deleteData($userId);
                    $modelUserrole = new Admin_Model_Userrole();
                    $modelUserrole->deleteData($userId);
                    // ghi log
                    if(file_exists(CONFIG_PATH . '/history.ini')){
                        $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                        
                        $dataHistory['userId']      = $this->_auth['userId'];
                        $dataHistory['time']        = time();
                        $dataHistory['url']         = $this->getRequest()->getRequestUri();
                        $dataHistory['module']      = 'admin';
                        $dataHistory['controller']  = 'user';
                        $dataHistory['action']      = 'delete';
                        $dataHistory['obj']         = 'user';
                        $dataHistory['objField']    = $userCheck['username'];
                        $dataHistory['objId']       = $userId;
                        $modelHistory = new Admin_Model_History();
                        $modelHistory->addData($dataHistory);
                    }
                }
                $this->_helper->redirector('index', 'user', 'admin');
            }else{
                
                if($this->_auth['userId'] == $userId){
                    $this->_helper->redirector('index', 'user', 'admin');
                    exit();
                }
            }
        }
    }
    public function addAction(){
        $form = new Admin_Form_User();
        $form->submit->setLabel('Thêm mới');
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $username   = $form->getValue('username');
                $password   = $form->getValue('password');
                $userRole   = $form->getValue('userRole');
                $status     = $form->getValue('status');
                
                $modelUser = new Admin_Model_User();
				if(strlen($password) < 6){
					$this->view->mess = "Mật khẩu tối thiểu 6 ký tự!!!";
                    $this->view->flag = "alert";
				}elseif($modelUser->getDataByUsername($username)){
					$this->view->mess = "Username đã tồn tại!!!";
                    $this->view->flag = "alert";
				}else{
					$userId = $modelUser->addData($username, $password, $status);
                    if($userId){
                        //Thêm các quyền của user
                        $count = count($userRole);
                    	$dataItem = array();
                    	for($i=0;$i<$count;++$i){
                    		if(!$userRole[$i]){
                    			continue;
                    		}
                    		$dataItem[] = '('.$userId . ',' . (int)($userRole[$i]).')';
                    	}
                        $modelUserrole = new Admin_Model_Userrole();
                		$modelUserrole->addMultiData($dataItem);
                        // ghi log
                        if(file_exists(CONFIG_PATH . '/history.ini')){
                            $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                            
                            $dataHistory['userId']      = $this->_auth['userId'];
                            $dataHistory['time']        = time();
                            $dataHistory['url']         = $this->getRequest()->getRequestUri();
                            $dataHistory['module']      = 'admin';
                            $dataHistory['controller']  = 'user';
                            $dataHistory['action']      = 'add';
                            $dataHistory['obj']         = 'user';
                            $dataHistory['objField']    = $username;
                            $dataHistory['objId']       = $userId;
                            $modelHistory = new Admin_Model_History();
                            $modelHistory->addData($dataHistory);
                        }
                    }
                    $this->_helper->redirector('index', 'user', 'admin');
				}

            }else{
                $form->populate($formData);
            }
        }
    }
    public function editAction(){
		$form = new Admin_Form_User();
		$form->submit->setLabel('Lưu thay đổi');
		$this->view->form = $form;

		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)){

				$dataUpdate['userId'] = (int)($form->getValue('userId'));
				$dataUpdate['username'] = $form->getValue('username');
				$dataUpdate['password'] = $form->getValue('password');
				$dataUpdate['userRole'] = $form->getValue('userRole');
                $dataUpdate['status']     = $form->getValue('status');

                $modelUser = new Admin_Model_User();
                $userCheck = $modelUser->getDataByUsername($dataUpdate['username']);
                if(!$userCheck || $userCheck['userId'] == $dataUpdate['userId']){
                    $check = 1;
				    if($dataUpdate['password']){
				        if(strlen($dataUpdate['password']) < 6){
				            $this->view->mess = "Mật khẩu tối thiểu 6 ký tự!!!";
                            $this->view->flag = "alert";
                            $check = 0;
                        }
    				}
                    if($check){
        				$modelUser->updateData($dataUpdate['userId'], $dataUpdate['username'], $dataUpdate['password'], $dataUpdate['status']);
                        
                        $modelUserrole = new Admin_Model_Userrole();
                        $modelUserrole->deleteData($dataUpdate['userId']);
                
                		$dataRole = array();
                		if(count($dataUpdate['userRole']) > 0){
                			for($i = 0; $i<count($dataUpdate['userRole']); $i++){
                				$dataRole[] =	'('. $dataUpdate['userId'] . ',' . $dataUpdate['userRole'][$i] .')';
                			}
                			$dataRole = array_unique($dataRole);
                
                            $modelUserrole->addMultiData($dataRole);
                		}
                        // ghi log
                        if(file_exists(CONFIG_PATH . '/history.ini')){
                            $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                            
                            $dataHistory['userId']      = $this->_auth['userId'];
                            $dataHistory['time']        = time();
                            $dataHistory['url']         = $this->getRequest()->getRequestUri();
                            $dataHistory['module']      = 'admin';
                            $dataHistory['controller']  = 'user';
                            $dataHistory['action']      = 'edit';
                            $dataHistory['obj']         = 'user';
                            $dataHistory['objField']    = $dataUpdate['username'];
                            $dataHistory['objId']       = $dataUpdate['userId'];
                            $dataHistory['valueField']  = array();
                            $dataHistory['valueOld']    = array();
                            $dataHistory['valueNew']    = array();
                            foreach($dataUpdate as $key=>$value){
                                if(isset($userCheck[$key]) && $value != $userCheck[$key] && $key != 'password'){
                                    $dataHistory['valueField'][] = $key;
                                    $dataHistory['valueOld'][] = $userCheck[$key];
                                    $dataHistory['valueNew'][] = $value;
                                }
                            }
                            if($dataHistory['valueField']){
                                $dataHistory['valueField']  = json_encode($dataHistory['valueField']);
                                $dataHistory['valueOld']    = json_encode($dataHistory['valueOld']);
                                $dataHistory['valueNew']    = json_encode($dataHistory['valueNew']);
                                $modelHistory = new Admin_Model_History();
                                $modelHistory->addData($dataHistory);
                            }
                        }
                        $this->_helper->redirector('index', 'user', 'admin');
                    }else{
                        $form->populate($formData);
                    }
                }else{
                    $this->view->mess ="Username đã tồn tại!!!";
                    $this->view->flag = "alert";
    				$form->populate($formData);
    			}

			}else{
				$form->populate($formData);
			}
		}else{
			$dataUpdate['userId'] = (int)($this->_getParam('id', 0));
                
            $modelUser = new Admin_Model_User();
			$userCheck = $modelUser->getDataByID($dataUpdate['userId']);
            if($userCheck){
                $modelRole = new Admin_Model_Role();
                $roleList = $modelRole->getDataByUserId($dataUpdate['userId'])->toArray();
                
    			$this->view->roleList = $roleList;
    			$this->view->userCheck = $userCheck;
    			$form->populate($userCheck->toArray());
            }else{
                $this->_helper->redirector('index', 'user', 'admin');
            }
		}
    }
}





